package com.boot.security;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.boot.dao.UserDao;
import com.boot.entity.Permission;
import com.boot.entity.User;
import lombok.AllArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author: zcs
 * @data: 2021/4/15
 * @description: 自己实现的UserDetailsService
 */
@AllArgsConstructor
@Component
public class CustomUserDetailsService implements UserDetailsService {

    private UserDao userDao;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (username == null || username.isEmpty()) {
            throw new UsernameNotFoundException("用户名不能为空");
        }
        User user = userDao.selectOne(new QueryWrapper<User>().lambda().eq(User::getUsername, username));
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        List<Permission> permissionList = userDao.selectPermissionsById(user.getId());

        if (permissionList != null && !permissionList.isEmpty()) {
            user.setPermissionList(permissionList);
        }
        return user;
    }
}
